package org.mat.ipaas.ucenter.service.modules.system.controller;


import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.biz.common.config.TenantContext;
import org.mat.ipaas.ucenter.biz.common.constant.CommonConstant;
import org.mat.ipaas.ucenter.biz.common.constant.SymbolConstant;
import org.mat.ipaas.ucenter.biz.common.system.query.QueryGenerator;
import org.mat.ipaas.ucenter.biz.common.util.PasswordUtil;
import org.mat.ipaas.ucenter.biz.common.util.oConvertUtils;
import org.mat.ipaas.ucenter.biz.config.mybatis.MybatisPlusSaasConfig;
import org.mat.ipaas.ucenter.biz.modules.base.service.BaseCommonService;
import org.mat.ipaas.ucenter.biz.modules.system.entity.*;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysTenantPackService;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysTenantService;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysUserService;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysUserTenantService;
import org.mat.ipaas.ucenter.biz.modules.system.vo.SysUserTenantVo;
import org.mat.ipaas.ucenter.biz.modules.system.vo.tenant.*;
import org.mat.ipaas.ucenter.service.api.system.SysTenantRestAPI;
import org.mat.ipaas.ucenter.service.dto.system.entity.*;
import org.mat.ipaas.ucenter.service.dto.system.vo.LoginUserDTO;
import org.mat.ipaas.ucenter.service.dto.system.vo.SysUserTenantVoDTO;
import org.mat.ipaas.ucenter.service.dto.system.vo.tenant.*;
import org.mat.ipaas.ucenter.service.modules.SessionService;
import org.mat.ipaas.ucenter.service.modules.TokenUtils;
import org.mat.ipaas.ucenter.service.modules.aop.PermissionData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 租户配置信息
 *
 */
@Slf4j
@RestController
@RequestMapping("/sys/tenant")
public class SysTenantController implements SysTenantRestAPI {

    @Autowired
    private SessionService sessionService;

    @Autowired
    private ISysTenantService sysTenantService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysUserTenantService relationService;

    @Autowired
    private ISysTenantPackService sysTenantPackService;

    @Autowired
    private BaseCommonService baseCommonService;

    /**
     * 获取列表数据
     *
     * @param sysTenantDTO
     * @param pageNo
     * @param pageSize
     * @return
     */
    //@RequiresPermissions("system:tenant:list")
    @PermissionData(pageComponent = "system/TenantList")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public MatApiResponse<Page<SysTenantDTO>> queryPageList(@SpringQueryMap SysTenantDTO sysTenantDTO,
                                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();

        MatApiResponse<Page<SysTenantDTO>> matApiResponse = new MatApiResponse<>();
        SysTenant sysTenant = toSysTenant(sysTenantDTO);

        //---author:zhangyafei---date:20210916-----for: 租户管理添加日期范围查询---
        Date beginDate = null;
        Date endDate = null;
        if (oConvertUtils.isNotEmpty(sysTenant)) {
            beginDate = sysTenant.getBeginDate();
            endDate = sysTenant.getEndDate();
            sysTenant.setBeginDate(null);
            sysTenant.setEndDate(null);
        }
        //---author:zhangyafei---date:20210916-----for: 租户管理添加日期范围查询---
        QueryWrapper<SysTenant> queryWrapper = QueryGenerator.initQueryWrapper(sysTenant, req.getParameterMap());
        //---author:zhangyafei---date:20210916-----for: 租户管理添加日期范围查询---
        if (oConvertUtils.isNotEmpty(sysTenant)) {
            queryWrapper.ge(oConvertUtils.isNotEmpty(beginDate), "begin_date", beginDate);
            queryWrapper.le(oConvertUtils.isNotEmpty(endDate), "end_date", endDate);
        }
        //---author:zhangyafei---date:20210916-----for: 租户管理添加日期范围查询---
        Page<SysTenant> page = new Page<SysTenant>(pageNo, pageSize);
        IPage<SysTenant> pageList = sysTenantService.page(page, queryWrapper);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysTenantDTOPage(pageList));
        return matApiResponse;
    }

    /**
     * 获取租户删除的列表
     *
     * @param sysTenantDTO
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/recycleBinPageList")
    //@RequiresPermissions("system:tenant:recycleBinPageList")
    public MatApiResponse<IPage<SysTenantDTO>> recycleBinPageList(@SpringQueryMap SysTenantDTO sysTenantDTO,
                                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attributes.getRequest();

        MatApiResponse<IPage<SysTenantDTO>> matApiResponse = new MatApiResponse<>();
        SysTenant sysTenant = toSysTenant(sysTenantDTO);

        Page<SysTenant> page = new Page<SysTenant>(pageNo, pageSize);
        IPage<SysTenant> pageList = sysTenantService.getRecycleBinPageList(page, sysTenant);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysTenantDTOPage(pageList));
        return matApiResponse;
    }

    /**
     * 添加
     *
     * @param
     * @return
     */
    //@RequiresPermissions("system:tenant:add")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public MatApiResponse<SysTenantDTO> add(@RequestBody SysTenantDTO sysTenantDTO) {
        MatApiResponse<SysTenantDTO> matApiResponse = new MatApiResponse<>();
        SysTenant sysTenant = toSysTenant(sysTenantDTO);

        if (sysTenantService.getById(sysTenant.getId()) != null) {
            return matApiResponse.fail("该编号已存在!");
        }
        try {
            sysTenantService.saveTenant(sysTenant);
            matApiResponse.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("操作失败");
        }
        return matApiResponse;
    }

    /**
     * 编辑
     *
     * @param
     * @return
     */
    //@RequiresPermissions("system:tenant:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public MatApiResponse<SysTenantDTO> edit(@RequestBody SysTenantDTO sysTenantDTO) {
        MatApiResponse<SysTenantDTO> matApiResponse = new MatApiResponse<>();
        SysTenant tenant = toSysTenant(sysTenantDTO);

        SysTenant sysTenant = sysTenantService.getById(tenant.getId());
        if (sysTenant == null) {
            return matApiResponse.fail("未找到对应实体");
        }
        if (oConvertUtils.isEmpty(sysTenant.getHouseNumber())) {
            tenant.setHouseNumber(RandomUtil.randomStringUpper(6));
        }
        boolean ok = sysTenantService.updateById(tenant);
        if (ok) {
            matApiResponse.success("修改成功!");
        }
        return matApiResponse;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    //@RequiresPermissions("system:tenant:delete")
    @RequestMapping(value = "/delete", method = {RequestMethod.DELETE, RequestMethod.POST})
    public MatApiResponse<?> delete(@RequestParam(name = "id", required = true) String id) {
        //------------------------------------------------------------------
        //如果是saas隔离的情况下，判断当前租户id是否是当前租户下的
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
            SysTenant sysTenant = sysTenantService.getById(id);

            String username = "admin";
            String createdBy = TokenUtils.getLoginUserName();
            if (!sysTenant.getCreateBy().equals(createdBy) && !username.equals(createdBy)) {
                baseCommonService.addLog("未经授权，不能删除非自己创建的租户，租户ID：" + id + "，操作人：" + createdBy, CommonConstant.LOG_TYPE_2, CommonConstant.OPERATE_TYPE_3);
                return MatApiResponse.fail("删除租户失败,当前操作人不是租户的创建人！");
            }
        }
        //------------------------------------------------------------------

        sysTenantService.removeTenantById(id);
        return MatApiResponse.success("删除成功");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    //@RequiresPermissions("system:tenant:deleteBatch")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public MatApiResponse<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        MatApiResponse<?> matApiResponse = new MatApiResponse<>();
        if (oConvertUtils.isEmpty(ids)) {
            matApiResponse.fail("未选中租户！");
        } else {
            String[] ls = ids.split(",");
            // 过滤掉已被引用的租户
            List<Integer> idList = new ArrayList<>();
            for (String id : ls) {
                //------------------------------------------------------------------
                //如果是saas隔离的情况下，判断当前租户id是否是当前租户下的
                if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
                    SysTenant sysTenant = sysTenantService.getById(id);

                    String username = "admin";
                    String createdBy = TokenUtils.getLoginUserName();
                    if (!sysTenant.getCreateBy().equals(createdBy) && !username.equals(createdBy)) {
                        baseCommonService.addLog("未经授权，不能删除非自己创建的租户，租户ID：" + id + "，操作人：" + createdBy, CommonConstant.LOG_TYPE_2, CommonConstant.OPERATE_TYPE_3);
                        return MatApiResponse.fail("删除租户失败,当前操作人不是租户的创建人！");
                    }
                }
                //------------------------------------------------------------------

                Long userCount = sysTenantService.countUserLinkTenant(id);
                if (userCount == 0) {
                    idList.add(Integer.parseInt(id));
                }
            }
            if (idList.size() > 0) {
                sysTenantService.removeByIds(idList);
                if (ls.length == idList.size()) {
                    matApiResponse.success("删除成功！");
                } else {
                    matApiResponse.success("部分删除成功！（被引用的租户无法删除）");
                }
            } else {
                matApiResponse.fail("选择的租户都已被引用，无法删除！");
            }
        }
        return matApiResponse;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public MatApiResponse<SysTenantDTO> queryById(@RequestParam(name = "id", required = true) String id) {
        MatApiResponse<SysTenantDTO> matApiResponse = new MatApiResponse<>();
        if (oConvertUtils.isEmpty(id)) {
            matApiResponse.fail("参数为空！");
        }
        //------------------------------------------------------------------------------------------------
        //获取登录用户信息
        String username = TokenUtils.getLoginUserName();

        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】, admin给特权可以管理所有租户
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL && !"admin".equals(username)) {
            Integer loginSessionTenant = oConvertUtils.getInt(TenantContext.getTenant());
            if (loginSessionTenant != null && !loginSessionTenant.equals(Integer.valueOf(id))) {
                matApiResponse.fail("无权限访问他人租户！");
                return matApiResponse;
            }
        }
        //------------------------------------------------------------------------------------------------
        SysTenant sysTenant = sysTenantService.getById(id);
        if (sysTenant == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            matApiResponse.setData(toSysTenantDTO(sysTenant));
            matApiResponse.setSuccess(true);
        }
        return matApiResponse;
    }

    /**
     * 查询有效的 租户数据
     *
     * @return
     */
    //@RequiresPermissions("system:tenant:queryList")
    @RequestMapping(value = "/queryList", method = RequestMethod.GET)
    public MatApiResponse<List<SysTenantDTO>> queryList(@RequestParam(name = "ids", required = false) String ids) {
        MatApiResponse<List<SysTenantDTO>> matApiResponse = new MatApiResponse<>();
        LambdaQueryWrapper<SysTenant> query = new LambdaQueryWrapper<>();
        query.eq(SysTenant::getStatus, 1);
        if (oConvertUtils.isNotEmpty(ids)) {
            query.in(SysTenant::getId, ids.split(","));
        }
        //此处查询忽略时间条件
        List<SysTenant> ls = sysTenantService.list(query);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysTenantDTOList(ls));
        return matApiResponse;
    }

    /**
     * 产品包分页列表查询
     *
     * @param sysTenantPackDTO
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/packList")
    //@RequiresPermissions("system:tenant:packList")
    public MatApiResponse<IPage<SysTenantPackDTO>> queryPackPageList(SysTenantPackDTO sysTenantPackDTO,
                                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                     HttpServletRequest req) {
        SysTenantPack sysTenantPack = toSysTenantPack(sysTenantPackDTO);

        QueryWrapper<SysTenantPack> queryWrapper = QueryGenerator.initQueryWrapper(sysTenantPack, req.getParameterMap());
        Page<SysTenantPack> page = new Page<SysTenantPack>(pageNo, pageSize);
        IPage<SysTenantPack> pageList = sysTenantPackService.page(page, queryWrapper);
        List<SysTenantPack> records = pageList.getRecords();
        if (null != records && records.size() > 0) {
            pageList.setRecords(sysTenantPackService.setPermissions(records));
        }
        return MatApiResponse.success(toSysTenantPackDTOPage(pageList));
    }

    /**
     * 创建租户产品包
     *
     * @param sysTenantPackDTO
     * @return
     */
    @PostMapping(value = "/addPackPermission")
    //@RequiresPermissions("system:tenant:add:pack")
    public MatApiResponse<String> addPackPermission(@RequestBody SysTenantPackDTO sysTenantPackDTO) {
        SysTenantPack sysTenantPack = toSysTenantPack(sysTenantPackDTO);

        sysTenantPackService.addPackPermission(sysTenantPack);
        return MatApiResponse.success("创建租户产品包成功");
    }

    /**
     * 创建租户产品包
     *
     * @param sysTenantPackDTO
     * @return
     */
    @PutMapping(value = "/editPackPermission")
    //@RequiresPermissions("system:tenant:edit:pack")
    public MatApiResponse<String> editPackPermission(@RequestBody SysTenantPackDTO sysTenantPackDTO) {
        SysTenantPack sysTenantPack = toSysTenantPack(sysTenantPackDTO);

        sysTenantPackService.editPackPermission(sysTenantPack);
        return MatApiResponse.success("修改租户产品包成功");
    }

    /**
     * 批量删除用户菜单
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/deletePackPermissions")
    //@RequiresPermissions("system:tenant:delete:pack")
    public MatApiResponse<String> deletePackPermissions(@RequestParam(value = "ids") String ids) {
        sysTenantPackService.deletePackPermissions(ids);
        return MatApiResponse.success("删除租户产品包成功");
    }


    //===========【低代码应用，前端专用接口 —— 加入限制只能维护和查看自己拥有的租户】==========================================================

    /**
     * 查询当前用户的所有有效租户【低代码应用专用接口】
     *
     * @return
     */
    @RequestMapping(value = "/getCurrentUserTenant", method = RequestMethod.GET)
    public MatApiResponse<Map<String, Object>> getCurrentUserTenant() {
        MatApiResponse<Map<String, Object>> matApiResponse = new MatApiResponse<Map<String, Object>>();
        try {
            LoginUserDTO sysUser = sessionService.getLoginUser();

            //update-begin---author:wangshuai ---date:20221223  for：[QQYUN-3371]租户逻辑改造，改成关系表------------
            List<Integer> tenantIdList = relationService.getTenantIdsByUserId(sysUser.getId());
            Map<String, Object> map = new HashMap(5);
            if (null != tenantIdList && tenantIdList.size() > 0) {
                //update-end---author:wangshuai ---date:20221223  for：[QQYUN-3371]租户逻辑改造，改成关系表------------
                // 该方法仅查询有效的租户，如果返回0个就说明所有的租户均无效。
                List<SysTenant> tenantList = sysTenantService.queryEffectiveTenant(tenantIdList);
                map.put("list", tenantList);
            }
            matApiResponse.setSuccess(true);
            matApiResponse.setData(map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("查询失败！");
        }
        return matApiResponse;
    }

    /**
     * 邀请用户【低代码应用专用接口】
     *
     * @param ids
     * @param phone
     * @return
     */
    @PutMapping("/invitationUserJoin")
    //@RequiresPermissions("system:tenant:invitation:user")
    public MatApiResponse<String> invitationUserJoin(@RequestParam("ids") String ids, @RequestParam("phone") String phone) {
        sysTenantService.invitationUserJoin(ids, phone);
        return MatApiResponse.success("邀请用户成功");
    }

    /**
     * 获取用户列表数据【低代码应用专用接口】
     *
     * @param sysUserDTO
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @RequestMapping(value = "/getTenantUserList", method = RequestMethod.GET)
    //@RequiresPermissions("system:tenant:user:list")
    public MatApiResponse<IPage<SysUserDTO>> getTenantUserList(SysUserDTO sysUserDTO,
                                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                               @RequestParam(name = "userTenantId") String userTenantId,
                                                               HttpServletRequest req) {
        MatApiResponse<IPage<SysUserDTO>> matApiResponse = new MatApiResponse<>();
        SysUser user = toSysUser(sysUserDTO);

        Page<SysUser> page = new Page<>(pageNo, pageSize);
        Page<SysUser> pageList = relationService.getPageUserList(page, Integer.valueOf(userTenantId), user);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(toSysUserDTOPage(pageList));
        return matApiResponse;
    }

    /**
     * 请离用户租户【低代码应用专用接口】
     *
     * @param userIds
     * @param tenantId
     * @return
     */
    @PutMapping("/leaveTenant")
    //@RequiresPermissions("system:tenant:leave")
    public MatApiResponse<String> leaveTenant(@RequestParam("userIds") String userIds,
                                              @RequestParam("tenantId") String tenantId) {
        MatApiResponse<String> matApiResponse = new MatApiResponse<>();
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        LoginUserDTO sysUser = sessionService.getLoginUser();
        ;
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL && !"admin".equals(sysUser.getUsername())) {
            Integer loginSessionTenant = oConvertUtils.getInt(TenantContext.getTenant());
            if (loginSessionTenant != null && !loginSessionTenant.equals(Integer.valueOf(tenantId))) {
                matApiResponse.fail("无权限访问他人租户！");
                return matApiResponse;
            }
        }
        sysTenantService.leaveTenant(userIds, tenantId);
        return MatApiResponse.success("请离成功");
    }

    /**
     * 编辑（只允许修改自己拥有的租户）【低代码应用专用接口】
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/editOwnTenant", method = {RequestMethod.PUT, RequestMethod.POST})
    public MatApiResponse<SysTenantDTO> editOwnTenant(@RequestBody SysTenantDTO sysTenantDTO, HttpServletRequest req) {
        MatApiResponse<SysTenantDTO> matApiResponse = new MatApiResponse<>();
        SysTenant tenant = toSysTenant(sysTenantDTO);

        String tenantId = TokenUtils.getTenantIdByRequest(req);
        if (!tenantId.equals(tenant.getId().toString())) {
            return matApiResponse.fail("无权修改他人租户！");
        }

        SysTenant sysTenant = sysTenantService.getById(tenant.getId());
        if (sysTenant == null) {
            return matApiResponse.fail("未找到对应实体");
        }
        if (oConvertUtils.isEmpty(sysTenant.getHouseNumber())) {
            tenant.setHouseNumber(RandomUtil.randomStringUpper(6));
        }
        boolean ok = sysTenantService.updateById(tenant);
        if (ok) {
            matApiResponse.success("修改成功!");
        }
        return matApiResponse;
    }

    /**
     * 创建租户并且将用户保存到中间表【低代码应用专用接口】
     *
     * @param sysTenantDTO
     */
    @PostMapping("/saveTenantJoinUser")
    public MatApiResponse<Integer> saveTenantJoinUser(@RequestBody SysTenantDTO sysTenantDTO) {
        MatApiResponse<Integer> matApiResponse = new MatApiResponse<>();
        SysTenant sysTenant = toSysTenant(sysTenantDTO);

        LoginUserDTO sysUser = sessionService.getLoginUser();
        ;
        //------------------------------------------------------------------------------------------------
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
            //---author:scott---date:20220111-----for: 限制免费用户只能创建两个租户--
            Integer count = sysTenantService.countCreateTenantNum(sysUser.getUsername());
            if (count > 2) {
                Set<String> roles = sysUserService.getUserRolesSet(sysUser.getUsername());
                //创建一个付费角色 paymember
                if (roles == null || (!roles.contains("paymember") && !roles.contains("admin"))) {
                    return matApiResponse.fail("免费用户最多创建两个租户!");
                }
            }
            //---author:scott---date:20220111-----for:  限制免费用户只能创建两个租户--
        }
        //------------------------------------------------------------------------------------------------
        Integer tenantId = sysTenantService.saveTenantJoinUser(sysTenant, sysUser.getId());
        matApiResponse.setSuccess(true);
        matApiResponse.setMessage("创建成功");
        matApiResponse.setData(tenantId);
        return matApiResponse;
    }

    /**
     * 加入租户通过门牌号【低代码应用专用接口】
     *
     * @param sysTenantDTO
     */
    @PostMapping("/joinTenantByHouseNumber")
    public MatApiResponse<Integer> joinTenantByHouseNumber(@RequestBody SysTenantDTO sysTenantDTO) {
        MatApiResponse<Integer> matApiResponse = new MatApiResponse<>();
        SysTenant sysTenant = toSysTenant(sysTenantDTO);

        LoginUserDTO sysUser = sessionService.getLoginUser();
        ;
        Integer tenantId = sysTenantService.joinTenantByHouseNumber(sysTenant, sysUser.getId());
        if (tenantId != 0) {
            matApiResponse.setMessage("申请租户成功");
            matApiResponse.setSuccess(true);
            matApiResponse.setData(tenantId);
            return matApiResponse;
        } else {
            matApiResponse.setMessage("该门牌号不存在");
            matApiResponse.setSuccess(false);
            return matApiResponse;
        }
    }

    //update-begin---author:wangshuai ---date:20230107  for：[QQYUN-3725]申请加入租户，审核中状态增加接口------------

    /**
     * 分页获取租户用户数据(vue3用户租户页面)【低代码应用专用接口】
     *
     * @param pageNo
     * @param pageSize
     * @param userTenantStatus
     * @param type
     * @return
     */
    @GetMapping("/getUserTenantPageList")
    //@RequiresPermissions("system:tenant:tenantPageList")
    public MatApiResponse<Page<SysUserTenantVoDTO>> getUserTenantPageList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                           @RequestParam(name = "userTenantStatus") String userTenantStatus,
                                                                           @RequestParam(name = "type", required = false) String type,
                                                                           @SpringQueryMap SysUserDTO sysUserDTO) {
        SysUser user = toSysUser(sysUserDTO);

        Page<SysUserTenantVo> page = new Page<>(pageNo, pageSize);
        LoginUserDTO sysUser = sessionService.getLoginUser();

        String tenantId = oConvertUtils.getString(TenantContext.getTenant(), "0");
        IPage<SysUserTenantVo> list = relationService.getUserTenantPageList(page, Arrays.asList(userTenantStatus.split(SymbolConstant.COMMA)), user, Integer.valueOf(tenantId));
        return MatApiResponse.success(toSysUserTenantVoDTOPage(list));
    }

    /**
     * 通过用户id获取租户列表【低代码应用专用接口】
     *
     * @param userTenantStatus 关系表的状态
     * @return
     */
    @GetMapping("/getTenantListByUserId")
    //@RequiresPermissions("system:tenant:getTenantListByUserId")
    public MatApiResponse<List<SysUserTenantVoDTO>> getTenantListByUserId(@RequestParam(name = "userTenantStatus", required = false) String userTenantStatus) {
        LoginUserDTO sysUser = sessionService.getLoginUser();

        List<String> list = null;
        if (oConvertUtils.isNotEmpty(userTenantStatus)) {
            list = Arrays.asList(userTenantStatus.split(SymbolConstant.COMMA));
        }
        //租户状态，用户id,租户用户关系状态
        List<SysUserTenantVo> sysTenant = relationService.getTenantListByUserId(sysUser.getId(), list);
        return MatApiResponse.success(toSysUserTenantVoDTOList(sysTenant));
    }

    /**
     * 更新用户租户关系状态【低代码应用专用接口】
     */
    @PutMapping("/updateUserTenantStatus")
    //@RequiresPermissions("system:tenant:updateUserTenantStatus")
    public MatApiResponse<String> updateUserTenantStatus(@RequestBody SysUserTenantDTO sysUserTenantDTO) {
        SysUserTenant userTenant = toSysUserTenant(sysUserTenantDTO);
        String tenantId = TenantContext.getTenant();
        if (oConvertUtils.isEmpty(tenantId)) {
            return MatApiResponse.fail("未找到当前租户信息");
        }
        relationService.updateUserTenantStatus(userTenant.getUserId(), tenantId, userTenant.getStatus());
        return MatApiResponse.success("更新用户租户状态成功");
    }

    /**
     * 注销租户【低代码应用专用接口】
     *
     * @param sysTenantDTO
     * @return
     */
    @PutMapping("/cancelTenant")
    //@RequiresPermissions("system:tenant:cancelTenant")
    public MatApiResponse<String> cancelTenant(@RequestBody SysTenantDTO sysTenantDTO, HttpServletRequest request) {
        SysTenant sysTenant = toSysTenant(sysTenantDTO);

        LoginUserDTO sysUser = sessionService.getLoginUser();

        SysTenant tenant = sysTenantService.getById(sysTenant.getId());
        if (null == tenant) {
            return MatApiResponse.fail("未找到当前租户信息");
        }
        if (!sysUser.getUsername().equals(tenant.getCreateBy())) {
            return MatApiResponse.fail("无权限，只能注销自己创建的租户！");
        }
        SysUser userById = sysUserService.getById(sysUser.getId());
        String loginPassword = request.getParameter("loginPassword");
        String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), loginPassword, userById.getSalt());
        if (!passwordEncode.equals(userById.getPassword())) {
            return MatApiResponse.fail("密码不正确");
        }
        sysTenantService.removeById(sysTenant.getId());
        return MatApiResponse.success("注销成功");
    }
    //update-end---author:wangshuai ---date:20230107  for：[QQYUN-3725]申请加入租户，审核中状态增加接口------------

    /**
     * 获取租户用户不同状态下的数量【低代码应用专用接口】
     *
     * @return
     */
    @GetMapping("/getTenantStatusCount")
    public MatApiResponse<Long> getTenantStatusCount(@RequestParam(value = "status", defaultValue = "1") String status, HttpServletRequest req) {
        String tenantId = TokenUtils.getTenantIdByRequest(req);
        if (null == tenantId) {
            return MatApiResponse.fail("未找到当前租户信息");
        }
        LambdaQueryWrapper<SysUserTenant> query = new LambdaQueryWrapper<>();
        query.eq(SysUserTenant::getTenantId, tenantId);
        query.eq(SysUserTenant::getStatus, status);
        long count = relationService.count(query);
        return MatApiResponse.success(count);
    }

    /**
     * 用户取消租户申请【低代码应用专用接口】
     *
     * @param tenantId
     * @return
     */
    @PutMapping("/cancelApplyTenant")
    public MatApiResponse<String> cancelApplyTenant(@RequestParam("tenantId") String tenantId) {
        LoginUserDTO sysUser = sessionService.getLoginUser();
        ;
        sysTenantService.leaveTenant(sysUser.getId(), tenantId);
        return MatApiResponse.success("取消申请成功");
    }

    //===========【低代码应用，前端专用接口 —— 加入限制只能维护和查看自己拥有的租户】==========================================================

    /**
     * 彻底删除租户
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/deleteLogicDeleted")
    //@RequiresPermissions("system:tenant:deleteTenantLogic")
    public MatApiResponse<String> deleteTenantLogic(@RequestParam("ids") String ids) {
        sysTenantService.deleteTenantLogic(ids);
        return MatApiResponse.success("彻底删除成功");
    }

    /**
     * 还原删除的租户
     *
     * @param ids
     * @return
     */
    @PutMapping("/revertTenantLogic")
    //@RequiresPermissions("system:tenant:revertTenantLogic")
    public MatApiResponse<String> revertTenantLogic(@RequestParam("ids") String ids) {
        sysTenantService.revertTenantLogic(ids);
        return MatApiResponse.success("还原成功");
    }

    /**
     * 退出租户【低代码应用专用接口】
     *
     * @param sysTenantDTO
     * @param request
     * @return
     */
    @DeleteMapping("/exitUserTenant")
    public MatApiResponse<String> exitUserTenant(@RequestBody SysTenantDTO sysTenantDTO, HttpServletRequest request) {
        SysTenant sysTenant = toSysTenant(sysTenantDTO);

        LoginUserDTO sysUser = sessionService.getLoginUser();
        ;
        //验证用户是否已存在
        Integer count = relationService.userTenantIzExist(sysUser.getId(), sysTenant.getId());
        if (count == 0) {
            return MatApiResponse.fail("此租户下没有当前用户");
        }
        //验证密码
        String loginPassword = request.getParameter("loginPassword");
        SysUser userById = sysUserService.getById(sysUser.getId());
        String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), loginPassword, userById.getSalt());
        if (!passwordEncode.equals(userById.getPassword())) {
            return MatApiResponse.fail("密码不正确");
        }
        //退出登录
        sysTenantService.exitUserTenant(sysUser.getId(), sysUser.getUsername(), String.valueOf(sysTenant.getId()));
        return MatApiResponse.success("退出租户成功");
    }

    /**
     * 变更租户拥有者【低代码应用专用接口】
     *
     * @param userId
     * @return
     */
    @PostMapping("/changeOwenUserTenant")
    public MatApiResponse<String> changeOwenUserTenant(@RequestParam("userId") String userId) {
        sysTenantService.changeOwenUserTenant(userId);
        return MatApiResponse.success("退出租户成功");
    }

    /**
     * 邀请用户到租户,通过手机号匹配 【低代码应用专用接口】
     *
     * @param phone
     * @return
     */
    @PostMapping("/invitationUser")
    public MatApiResponse<String> invitationUser(@RequestParam(name = "phone") String phone) {
        return sysTenantService.invitationUser(phone);
    }


    /**
     * 获取 租户产品包-3个默认admin的人员数量
     *
     * @param tenantId
     * @return
     */
    @GetMapping("/loadAdminPackCount")
    public MatApiResponse<List<TenantPackUserCountDTO>> loadAdminPackCount(@RequestParam("tenantId") Integer tenantId) {
        List<TenantPackUserCount> list = sysTenantService.queryTenantPackUserCount(tenantId);
        return MatApiResponse.success(toTenantPackUserCountDTOList(list));
    }

    /**
     * 查询租户产品包信息
     *
     * @param tenantPackModelDTO
     * @return
     */
    @GetMapping("/getTenantPackInfo")
    public MatApiResponse<TenantPackModelDTO> getTenantPackInfo(TenantPackModelDTO tenantPackModelDTO) {
        TenantPackModel packModel = toTenantPackModel(tenantPackModelDTO);

        TenantPackModel tenantPackModel = sysTenantService.queryTenantPack(packModel);
        return MatApiResponse.success(toTenantPackModelDTO(tenantPackModel));
    }


    /**
     * 添加用户和产品包的关系数据
     *
     * @param sysTenantPackUserDTO
     * @return
     */
    @PostMapping("/addTenantPackUser")
    public MatApiResponse<?> addTenantPackUser(@RequestBody SysTenantPackUserDTO sysTenantPackUserDTO) {
        SysTenantPackUser sysTenantPackUser = toSysTenantPackUser(sysTenantPackUserDTO);

        sysTenantService.addBatchTenantPackUser(sysTenantPackUser);
        return MatApiResponse.success("操作成功！");
    }

    /**
     * 从产品包移除用户
     *
     * @param sysTenantPackUserDTO
     * @return
     */
    @PutMapping("/deleteTenantPackUser")
    public MatApiResponse<?> deleteTenantPackUser(@RequestBody SysTenantPackUserDTO sysTenantPackUserDTO) {
        SysTenantPackUser sysTenantPackUser = toSysTenantPackUser(sysTenantPackUserDTO);

        sysTenantService.deleteTenantPackUser(sysTenantPackUser);
        return MatApiResponse.success("操作成功！");
    }


    /**
     * 修改申请状态
     *
     * @param sysTenantDTO
     * @return
     */
    @PutMapping("/updateApplyStatus")
    public MatApiResponse<?> updateApplyStatus(@RequestBody SysTenantDTO sysTenantDTO) {
        SysTenant sysTenant = toSysTenant(sysTenantDTO);

        SysTenant entity = this.sysTenantService.getById(sysTenant.getId());
        if (entity == null) {
            return MatApiResponse.fail("租户不存在!");
        }
        entity.setApplyStatus(sysTenant.getApplyStatus());
        sysTenantService.updateById(entity);
        return MatApiResponse.success("");
    }


    /**
     * 获取产品包人员申请列表
     *
     * @param tenantId
     * @return
     */
    @GetMapping("/getTenantPackApplyUsers")
    public MatApiResponse<?> getTenantPackApplyUsers(@RequestParam("tenantId") Integer tenantId) {
        List<TenantPackUser> list = sysTenantService.getTenantPackApplyUsers(tenantId);
        return MatApiResponse.success(list);
    }

    /**
     * 个人 申请成为管理员
     *
     * @param sysTenantPackUserDTO
     * @return
     */
    @PostMapping("/doApplyTenantPackUser")
    public MatApiResponse<?> doApplyTenantPackUser(@RequestBody SysTenantPackUserDTO sysTenantPackUserDTO) {
        SysTenantPackUser sysTenantPackUser = toSysTenantPackUser(sysTenantPackUserDTO);

        sysTenantService.doApplyTenantPackUser(sysTenantPackUser);
        return MatApiResponse.success("申请成功！");
    }

    /**
     * 申请通过 成为管理员
     *
     * @param sysTenantPackUserDTO
     * @return
     */
    @PutMapping("/passApply")
    public MatApiResponse<?> passApply(@RequestBody SysTenantPackUserDTO sysTenantPackUserDTO) {
        SysTenantPackUser sysTenantPackUser = toSysTenantPackUser(sysTenantPackUserDTO);

        sysTenantService.passApply(sysTenantPackUser);
        return MatApiResponse.success("操作成功！");
    }

    /**
     * 拒绝申请 成为管理员
     *
     * @param sysTenantPackUserDTO
     * @return
     */
    @PutMapping("/deleteApply")
    public MatApiResponse<?> deleteApply(@RequestBody SysTenantPackUserDTO sysTenantPackUserDTO) {
        SysTenantPackUser sysTenantPackUser = toSysTenantPackUser(sysTenantPackUserDTO);

        sysTenantService.deleteApply(sysTenantPackUser);
        return MatApiResponse.success("");
    }


    /**
     * 进入应用组织页面 查询租户信息及当前用户是否有 管理员的权限--
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryTenantAuthInfo", method = RequestMethod.GET)
    public MatApiResponse<TenantDepartAuthInfoDTO> queryTenantAuthInfo(@RequestParam(name = "id", required = true) String id) {
        TenantDepartAuthInfo info = sysTenantService.getTenantDepartAuthInfo(Integer.parseInt(id));
        return MatApiResponse.success(toTenantDepartAuthInfoDTO(info));
    }

    /**
     * 获取产品包下的用户列表(分页)
     *
     * @param tenantId
     * @param packId
     * @param status
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/queryTenantPackUserList")
    public MatApiResponse<IPage<TenantPackUserDTO>> queryTenantPackUserList(@RequestParam("tenantId") String tenantId,
                                                                            @RequestParam("packId") String packId,
                                                                            @RequestParam("status") Integer status,
                                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<TenantPackUser> page = new Page<>(pageNo, pageSize);
        IPage<TenantPackUser> pageList = sysTenantService.queryTenantPackUserList(tenantId, packId, status, page);
        return MatApiResponse.success(toTenantPackUserDTOPage(pageList));
    }

    private Page<TenantPackUserDTO> toTenantPackUserDTOPage(IPage<TenantPackUser> pageList) {
        Page<TenantPackUserDTO> tenantPackUserDTOPage = new Page<>();
        List<TenantPackUserDTO> tenantPackUserDTOList = new ArrayList<>();
        if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())) {
            for (TenantPackUser tenantPackUser : pageList.getRecords()) {
                tenantPackUserDTOList.add(toTenantPackUserDTO(tenantPackUser));
            }
        }

        tenantPackUserDTOPage.setTotal(pageList.getTotal());
        tenantPackUserDTOPage.setSize(pageList.getSize());
        tenantPackUserDTOPage.setCurrent(pageList.getCurrent());
        tenantPackUserDTOPage.setRecords(tenantPackUserDTOList);
        return tenantPackUserDTOPage;
    }


    private Page<SysTenantDTO> toSysTenantDTOPage(IPage<SysTenant> pageList) {
        Page<SysTenantDTO> sysTenantDTOPage = new Page<>();
        List<SysTenantDTO> sysTenantDTOList = new ArrayList<>();
        if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())) {
            for (SysTenant sysTenant : pageList.getRecords()) {
                sysTenantDTOList.add(toSysTenantDTO(sysTenant));
            }
        }

        sysTenantDTOPage.setTotal(pageList.getTotal());
        sysTenantDTOPage.setSize(pageList.getSize());
        sysTenantDTOPage.setCurrent(pageList.getCurrent());
        sysTenantDTOPage.setRecords(sysTenantDTOList);
        return sysTenantDTOPage;
    }

    private SysTenantDTO toSysTenantDTO(SysTenant sysTenant) {
        if (sysTenant == null) {
            return null;
        }
        SysTenantDTO sysTenantDTO = new SysTenantDTO();
        sysTenantDTO.setId(sysTenant.getId());
        sysTenantDTO.setName(sysTenant.getName());
        sysTenantDTO.setCreateBy(sysTenant.getCreateBy());
        sysTenantDTO.setCreateTime(sysTenant.getCreateTime());
        sysTenantDTO.setBeginDate(sysTenant.getBeginDate());
        sysTenantDTO.setEndDate(sysTenant.getEndDate());
        sysTenantDTO.setStatus(sysTenant.getStatus());
        sysTenantDTO.setTrade(sysTenant.getTrade());
        sysTenantDTO.setCompanySize(sysTenant.getCompanySize());
        sysTenantDTO.setCompanyAddress(sysTenant.getCompanyAddress());
        sysTenantDTO.setCompanyLogo(sysTenant.getCompanyLogo());
        sysTenantDTO.setHouseNumber(sysTenant.getHouseNumber());
        sysTenantDTO.setWorkPlace(sysTenant.getWorkPlace());
        sysTenantDTO.setSecondaryDomain(sysTenant.getSecondaryDomain());
        sysTenantDTO.setLoginBkgdImg(sysTenant.getLoginBkgdImg());
        sysTenantDTO.setPosition(sysTenant.getPosition());
        sysTenantDTO.setDepartment(sysTenant.getDepartment());
        sysTenantDTO.setDelFlag(sysTenant.getDelFlag());
        sysTenantDTO.setUpdateBy(sysTenant.getUpdateBy());
        sysTenantDTO.setUpdateTime(sysTenant.getUpdateTime());
        sysTenantDTO.setApplyStatus(sysTenant.getApplyStatus());
        return sysTenantDTO;
    }

    private SysTenant toSysTenant(SysTenantDTO sysTenantDTO) {
        if (sysTenantDTO == null) {
            return null;
        }
        SysTenant sysTenant = new SysTenant();
        sysTenant.setId(sysTenantDTO.getId());
        sysTenant.setName(sysTenantDTO.getName());
        sysTenant.setCreateBy(sysTenantDTO.getCreateBy());
        sysTenant.setCreateTime(sysTenantDTO.getCreateTime());
        sysTenant.setBeginDate(sysTenantDTO.getBeginDate());
        sysTenant.setEndDate(sysTenantDTO.getEndDate());
        sysTenant.setStatus(sysTenantDTO.getStatus());
        sysTenant.setTrade(sysTenantDTO.getTrade());
        sysTenant.setCompanySize(sysTenantDTO.getCompanySize());
        sysTenant.setCompanyAddress(sysTenantDTO.getCompanyAddress());
        sysTenant.setCompanyLogo(sysTenantDTO.getCompanyLogo());
        sysTenant.setHouseNumber(sysTenantDTO.getHouseNumber());
        sysTenant.setWorkPlace(sysTenantDTO.getWorkPlace());
        sysTenant.setSecondaryDomain(sysTenantDTO.getSecondaryDomain());
        sysTenant.setLoginBkgdImg(sysTenantDTO.getLoginBkgdImg());
        sysTenant.setPosition(sysTenantDTO.getPosition());
        sysTenant.setDepartment(sysTenantDTO.getDepartment());
        sysTenant.setDelFlag(sysTenantDTO.getDelFlag());
        sysTenant.setUpdateBy(sysTenantDTO.getUpdateBy());
        sysTenant.setUpdateTime(sysTenantDTO.getUpdateTime());
        sysTenant.setApplyStatus(sysTenantDTO.getApplyStatus());
        return sysTenant;
    }

    private List<SysTenantDTO> toSysTenantDTOList(List<SysTenant> ls) {
        List<SysTenantDTO> sysTenantDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ls)) {
            for (SysTenant sysTenant : ls) {
                sysTenantDTOList.add(toSysTenantDTO(sysTenant));
            }
        }
        return sysTenantDTOList;
    }


    private Page<SysTenantPackDTO> toSysTenantPackDTOPage(IPage<SysTenantPack> pageList) {
        Page<SysTenantPackDTO> sysTenantPackDTOPage = new Page<>();
        List<SysTenantPackDTO> sysTenantPackDTOList = new ArrayList<>();
        if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())) {
            for (SysTenantPack sysTenantPack : pageList.getRecords()) {
                sysTenantPackDTOList.add(toSysTenantPackDTO(sysTenantPack));
            }
        }

        sysTenantPackDTOPage.setTotal(pageList.getTotal());
        sysTenantPackDTOPage.setSize(pageList.getSize());
        sysTenantPackDTOPage.setCurrent(pageList.getCurrent());
        sysTenantPackDTOPage.setRecords(sysTenantPackDTOList);
        return sysTenantPackDTOPage;
    }

    private SysTenantPackDTO toSysTenantPackDTO(SysTenantPack sysTenantPack) {
        if (sysTenantPack == null) {
            return null;
        }
        SysTenantPackDTO sysTenantPackDTO = new SysTenantPackDTO();
        sysTenantPackDTO.setId(sysTenantPack.getId());
        sysTenantPackDTO.setTenantId(sysTenantPack.getTenantId());
        sysTenantPackDTO.setPackName(sysTenantPack.getPackName());
        sysTenantPackDTO.setStatus(sysTenantPack.getStatus());
        sysTenantPackDTO.setRemarks(sysTenantPack.getRemarks());
        sysTenantPackDTO.setCreateBy(sysTenantPack.getCreateBy());
        sysTenantPackDTO.setCreateTime(sysTenantPack.getCreateTime());
        sysTenantPackDTO.setUpdateBy(sysTenantPack.getUpdateBy());
        sysTenantPackDTO.setUpdateTime(sysTenantPack.getUpdateTime());
        sysTenantPackDTO.setPermissionIds(sysTenantPack.getPermissionIds());
        sysTenantPackDTO.setPackCode(sysTenantPack.getPackCode());
        return sysTenantPackDTO;
    }

    private SysTenantPack toSysTenantPack(SysTenantPackDTO sysTenantPackDTO) {
        if (sysTenantPackDTO == null) {
            return null;
        }
        SysTenantPack sysTenantPack = new SysTenantPack();
        sysTenantPack.setId(sysTenantPackDTO.getId());
        sysTenantPack.setTenantId(sysTenantPackDTO.getTenantId());
        sysTenantPack.setPackName(sysTenantPackDTO.getPackName());
        sysTenantPack.setStatus(sysTenantPackDTO.getStatus());
        sysTenantPack.setRemarks(sysTenantPackDTO.getRemarks());
        sysTenantPack.setCreateBy(sysTenantPackDTO.getCreateBy());
        sysTenantPack.setCreateTime(sysTenantPackDTO.getCreateTime());
        sysTenantPack.setUpdateBy(sysTenantPackDTO.getUpdateBy());
        sysTenantPack.setUpdateTime(sysTenantPackDTO.getUpdateTime());
        sysTenantPack.setPermissionIds(sysTenantPackDTO.getPermissionIds());
        sysTenantPack.setPackCode(sysTenantPackDTO.getPackCode());
        return sysTenantPack;
    }


    private Page<SysUserDTO> toSysUserDTOPage(IPage<SysUser> pageList) {
        Page<SysUserDTO> sysUserDTOPage = new Page<>();
        List<SysUserDTO> sysUserDTOList = new ArrayList<>();
        if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())) {
            for (SysUser sysUser : pageList.getRecords()) {
                sysUserDTOList.add(toSysUserDTO(sysUser));
            }
        }

        sysUserDTOPage.setTotal(pageList.getTotal());
        sysUserDTOPage.setSize(pageList.getSize());
        sysUserDTOPage.setCurrent(pageList.getCurrent());
        sysUserDTOPage.setRecords(sysUserDTOList);
        return sysUserDTOPage;
    }

    private SysUserDTO toSysUserDTO(SysUser sysUser) {
        if (sysUser == null) {
            return null;
        }
        SysUserDTO sysUserDTO = new SysUserDTO();
        sysUserDTO.setId(sysUser.getId());
        sysUserDTO.setUsername(sysUser.getUsername());
        sysUserDTO.setRealname(sysUser.getRealname());
        sysUserDTO.setPassword(sysUser.getPassword());
        sysUserDTO.setSalt(sysUser.getSalt());
        sysUserDTO.setAvatar(sysUser.getAvatar());
        sysUserDTO.setBirthday(sysUser.getBirthday());
        sysUserDTO.setSex(sysUser.getSex());
        sysUserDTO.setEmail(sysUser.getEmail());
        sysUserDTO.setPhone(sysUser.getPhone());
        sysUserDTO.setOrgCode(sysUser.getOrgCode());
        sysUserDTO.setLoginTenantId(sysUser.getLoginTenantId());
        sysUserDTO.setOrgCodeTxt(sysUser.getOrgCodeTxt());
        sysUserDTO.setStatus(sysUser.getStatus());
        sysUserDTO.setDelFlag(sysUser.getDelFlag());
        sysUserDTO.setWorkNo(sysUser.getWorkNo());
        sysUserDTO.setPost(sysUser.getPost());
        sysUserDTO.setTelephone(sysUser.getTelephone());
        sysUserDTO.setCreateBy(sysUser.getCreateBy());
        sysUserDTO.setCreateTime(sysUser.getCreateTime());
        sysUserDTO.setUpdateBy(sysUser.getUpdateBy());
        sysUserDTO.setUpdateTime(sysUser.getUpdateTime());
        sysUserDTO.setActivitiSync(sysUser.getActivitiSync());
        sysUserDTO.setUserIdentity(sysUser.getUserIdentity());
        sysUserDTO.setDepartIds(sysUser.getDepartIds());
        sysUserDTO.setRelTenantIds(sysUser.getRelTenantIds());
        sysUserDTO.setClientId(sysUser.getClientId());
        sysUserDTO.setHomePath(sysUser.getHomePath());
        sysUserDTO.setPostText(sysUser.getPostText());
        sysUserDTO.setBpmStatus(sysUser.getBpmStatus());
        return sysUserDTO;
    }

    private SysUser toSysUser(SysUserDTO sysUserDTO) {
        if (sysUserDTO == null) {
            return null;
        }
        SysUser sysUser = new SysUser();
        sysUser.setId(sysUserDTO.getId());
        sysUser.setUsername(sysUserDTO.getUsername());
        sysUser.setRealname(sysUserDTO.getRealname());
        sysUser.setPassword(sysUserDTO.getPassword());
        sysUser.setSalt(sysUserDTO.getSalt());
        sysUser.setAvatar(sysUserDTO.getAvatar());
        sysUser.setBirthday(sysUserDTO.getBirthday());
        sysUser.setSex(sysUserDTO.getSex());
        sysUser.setEmail(sysUserDTO.getEmail());
        sysUser.setPhone(sysUserDTO.getPhone());
        sysUser.setOrgCode(sysUserDTO.getOrgCode());
        sysUser.setLoginTenantId(sysUserDTO.getLoginTenantId());
        sysUser.setOrgCodeTxt(sysUserDTO.getOrgCodeTxt());
        sysUser.setStatus(sysUserDTO.getStatus());
        sysUser.setDelFlag(sysUserDTO.getDelFlag());
        sysUser.setWorkNo(sysUserDTO.getWorkNo());
        sysUser.setPost(sysUserDTO.getPost());
        sysUser.setTelephone(sysUserDTO.getTelephone());
        sysUser.setCreateBy(sysUserDTO.getCreateBy());
        sysUser.setCreateTime(sysUserDTO.getCreateTime());
        sysUser.setUpdateBy(sysUserDTO.getUpdateBy());
        sysUser.setUpdateTime(sysUserDTO.getUpdateTime());
        sysUser.setActivitiSync(sysUserDTO.getActivitiSync());
        sysUser.setUserIdentity(sysUserDTO.getUserIdentity());
        sysUser.setDepartIds(sysUserDTO.getDepartIds());
        sysUser.setRelTenantIds(sysUserDTO.getRelTenantIds());
        sysUser.setClientId(sysUserDTO.getClientId());
        sysUser.setHomePath(sysUserDTO.getHomePath());
        sysUser.setPostText(sysUserDTO.getPostText());
        sysUser.setBpmStatus(sysUserDTO.getBpmStatus());
        return sysUser;
    }


    private Page<SysUserTenantVoDTO> toSysUserTenantVoDTOPage(IPage<SysUserTenantVo> pageList) {
        Page<SysUserTenantVoDTO> sysUserTenantVoDTOPage = new Page<>();
        List<SysUserTenantVoDTO> sysUserTenantVoDTOList = new ArrayList<>();
        if (pageList != null && CollectionUtils.isNotEmpty(pageList.getRecords())) {
            for (SysUserTenantVo sysUserTenantVo : pageList.getRecords()) {
                sysUserTenantVoDTOList.add(toSysUserTenantVoDTO(sysUserTenantVo));
            }
        }

        sysUserTenantVoDTOPage.setTotal(pageList.getTotal());
        sysUserTenantVoDTOPage.setSize(pageList.getSize());
        sysUserTenantVoDTOPage.setCurrent(pageList.getCurrent());
        sysUserTenantVoDTOPage.setRecords(sysUserTenantVoDTOList);
        return sysUserTenantVoDTOPage;
    }

    private SysUserTenantVoDTO toSysUserTenantVoDTO(SysUserTenantVo sysUserTenantVo) {
        if (sysUserTenantVo == null) {
            return null;
        }
        SysUserTenantVoDTO sysUserTenantVoDTO = new SysUserTenantVoDTO();
        sysUserTenantVoDTO.setId(sysUserTenantVo.getId());
        sysUserTenantVoDTO.setUsername(sysUserTenantVo.getUsername());
        sysUserTenantVoDTO.setRealname(sysUserTenantVo.getRealname());
        sysUserTenantVoDTO.setWorkNo(sysUserTenantVo.getWorkNo());
        sysUserTenantVoDTO.setEmail(sysUserTenantVo.getEmail());
        sysUserTenantVoDTO.setPhone(sysUserTenantVo.getPhone());
        sysUserTenantVoDTO.setAvatar(sysUserTenantVo.getAvatar());
        sysUserTenantVoDTO.setPost(sysUserTenantVo.getPost());
        sysUserTenantVoDTO.setStatus(sysUserTenantVo.getStatus());
        sysUserTenantVoDTO.setOrgCodeTxt(sysUserTenantVo.getOrgCodeTxt());
        sysUserTenantVoDTO.setOrgCode(sysUserTenantVo.getOrgCode());
        sysUserTenantVoDTO.setRelTenantIds(sysUserTenantVo.getRelTenantIds());
        sysUserTenantVoDTO.setCreateBy(sysUserTenantVo.getCreateBy());
        sysUserTenantVoDTO.setUserTenantStatus(sysUserTenantVo.getUserTenantStatus());
        sysUserTenantVoDTO.setTenantUserId(sysUserTenantVo.getTenantUserId());
        sysUserTenantVoDTO.setName(sysUserTenantVo.getName());
        sysUserTenantVoDTO.setTrade(sysUserTenantVo.getTrade());
        sysUserTenantVoDTO.setHouseNumber(sysUserTenantVo.getHouseNumber());
        return sysUserTenantVoDTO;
    }

    private List<SysUserTenantVoDTO> toSysUserTenantVoDTOList(List<SysUserTenantVo> tenantVoList) {
        List<SysUserTenantVoDTO> sysUserTenantVoDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(tenantVoList)) {
            for (SysUserTenantVo sysUserTenantVo : tenantVoList) {
                sysUserTenantVoDTOList.add(toSysUserTenantVoDTO(sysUserTenantVo));
            }
        }
        return sysUserTenantVoDTOList;
    }


    private SysUserTenant toSysUserTenant(SysUserTenantDTO sysUserTenantDTO) {
        if (sysUserTenantDTO == null) {
            return null;
        }
        SysUserTenant sysUserTenant = new SysUserTenant();
        sysUserTenant.setId(sysUserTenantDTO.getId());
        sysUserTenant.setUserId(sysUserTenantDTO.getUserId());
        sysUserTenant.setTenantId(sysUserTenantDTO.getTenantId());
        sysUserTenant.setStatus(sysUserTenantDTO.getStatus());
        sysUserTenant.setCreateBy(sysUserTenantDTO.getCreateBy());
        sysUserTenant.setCreateTime(sysUserTenantDTO.getCreateTime());
        sysUserTenant.setUpdateBy(sysUserTenantDTO.getUpdateBy());
        sysUserTenant.setUpdateTime(sysUserTenantDTO.getUpdateTime());
        return sysUserTenant;
    }

    private List<TenantPackUserCountDTO> toTenantPackUserCountDTOList(List<TenantPackUserCount> list) {
        List<TenantPackUserCountDTO> tenantPackUserCountDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (TenantPackUserCount tenantPackUserCount : list) {
                tenantPackUserCountDTOList.add(toTenantPackUserCountDTO(tenantPackUserCount));
            }
        }

        return tenantPackUserCountDTOList;
    }

    private TenantPackUserCountDTO toTenantPackUserCountDTO(TenantPackUserCount tenantPackUserCount) {
        if (tenantPackUserCount == null) {
            return null;
        }
        TenantPackUserCountDTO tenantPackUserCountDTO = new TenantPackUserCountDTO();
        tenantPackUserCountDTO.setPackCode(tenantPackUserCount.getPackCode());
        tenantPackUserCountDTO.setUserCount(tenantPackUserCount.getUserCount());
        return tenantPackUserCountDTO;
    }

    private TenantPackModelDTO toTenantPackModelDTO(TenantPackModel tenantPackModel) {
        if (tenantPackModel == null) {
            return null;
        }
        TenantPackModelDTO tenantPackModelDTO = new TenantPackModelDTO();
        tenantPackModelDTO.setTenantId(tenantPackModel.getTenantId());
        tenantPackModelDTO.setPackCode(tenantPackModel.getPackCode());
        tenantPackModelDTO.setPackId(tenantPackModel.getPackId());
        tenantPackModelDTO.setPackName(tenantPackModel.getPackName());
        tenantPackModelDTO.setAuthList(toTenantPackAuthDTOList(tenantPackModel.getAuthList()));
        tenantPackModelDTO.setUserList(toTenantPackUserDTOList(tenantPackModel.getUserList()));
        tenantPackModelDTO.setPackUserStatus(tenantPackModel.getPackUserStatus());
        return tenantPackModelDTO;
    }

    private List<TenantPackUserDTO> toTenantPackUserDTOList(List<TenantPackUser> userList) {
        List<TenantPackUserDTO> tenantPackUserDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(userList)) {
            for (TenantPackUser tenantPackUser : userList) {
                tenantPackUserDTOList.add(toTenantPackUserDTO(tenantPackUser));
            }
        }
        return tenantPackUserDTOList;
    }

    private TenantPackUserDTO toTenantPackUserDTO(TenantPackUser tenantPackUser) {
        if (tenantPackUser == null) {
            return null;
        }
        TenantPackUserDTO tenantPackUserDTO = new TenantPackUserDTO();
        tenantPackUserDTO.setId(tenantPackUser.getId());
        tenantPackUserDTO.setUsername(tenantPackUser.getUsername());
        tenantPackUserDTO.setRealname(tenantPackUser.getRealname());
        tenantPackUserDTO.setAvatar(tenantPackUser.getAvatar());
        tenantPackUserDTO.setPhone(tenantPackUser.getPhone());
        tenantPackUserDTO.setDepartNames(tenantPackUser.getDepartNames());
        tenantPackUserDTO.setPositionNames(tenantPackUser.getPositionNames());
        tenantPackUserDTO.setPackName(tenantPackUser.getPackName());
        tenantPackUserDTO.setPackId(tenantPackUser.getPackId());
        return tenantPackUserDTO;
    }

    private List<TenantPackAuthDTO> toTenantPackAuthDTOList(List<TenantPackAuth> authList) {
        List<TenantPackAuthDTO> tenantPackAuthDTOList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(authList)) {
            for (TenantPackAuth tenantPackAuth : authList) {
                tenantPackAuthDTOList.add(toTenantPackAuthDTO(tenantPackAuth));
            }
        }
        return tenantPackAuthDTOList;
    }

    private TenantPackAuthDTO toTenantPackAuthDTO(TenantPackAuth tenantPackAuth) {
        if (tenantPackAuth == null) {
            return null;
        }
        TenantPackAuthDTO tenantPackAuthDTO = new TenantPackAuthDTO();
        tenantPackAuthDTO.setCategory(tenantPackAuth.getCategory());
        tenantPackAuthDTO.setAuthName(tenantPackAuth.getAuthName());
        tenantPackAuthDTO.setAuthNote(tenantPackAuth.getAuthNote());
        return tenantPackAuthDTO;
    }

    private TenantPackModel toTenantPackModel(TenantPackModelDTO tenantPackModelDTO) {
        if (tenantPackModelDTO == null) {
            return null;
        }
        TenantPackModel tenantPackModel = new TenantPackModel();
        tenantPackModel.setTenantId(tenantPackModelDTO.getTenantId());
        tenantPackModel.setPackCode(tenantPackModelDTO.getPackCode());
        tenantPackModel.setPackId(tenantPackModelDTO.getPackId());
        tenantPackModel.setPackName(tenantPackModelDTO.getPackName());
        tenantPackModel.setAuthList(toTenantPackAuthList(tenantPackModelDTO.getAuthList()));
        tenantPackModel.setUserList(toTenantPackUserList(tenantPackModelDTO.getUserList()));
        tenantPackModel.setPackUserStatus(tenantPackModelDTO.getPackUserStatus());
        return tenantPackModel;
    }

    private List<TenantPackUser> toTenantPackUserList(List<TenantPackUserDTO> userList) {
        List<TenantPackUser> tenantPackUserList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(userList)) {
            for (TenantPackUserDTO tenantPackUserDTO : userList) {
                tenantPackUserList.add(toTenantPackUser(tenantPackUserDTO));
            }
        }
        return tenantPackUserList;
    }

    private TenantPackUser toTenantPackUser(TenantPackUserDTO tenantPackUserDTO) {
        if (tenantPackUserDTO == null) {
            return null;
        }
        TenantPackUser tenantPackUser = new TenantPackUser();
        tenantPackUser.setId(tenantPackUserDTO.getId());
        tenantPackUser.setUsername(tenantPackUserDTO.getUsername());
        tenantPackUser.setRealname(tenantPackUserDTO.getRealname());
        tenantPackUser.setAvatar(tenantPackUserDTO.getAvatar());
        tenantPackUser.setPhone(tenantPackUserDTO.getPhone());
        tenantPackUser.setDepartNames(tenantPackUserDTO.getDepartNames());
        tenantPackUser.setPositionNames(tenantPackUserDTO.getPositionNames());
        tenantPackUser.setPackName(tenantPackUserDTO.getPackName());
        tenantPackUser.setPackId(tenantPackUserDTO.getPackId());
        return tenantPackUser;
    }

    private List<TenantPackAuth> toTenantPackAuthList(List<TenantPackAuthDTO> authList) {
        List<TenantPackAuth> tenantPackAuthList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(authList)) {
            for (TenantPackAuthDTO tenantPackAuthDTO : authList) {
                tenantPackAuthList.add(toTenantPackAuth(tenantPackAuthDTO));
            }
        }
        return tenantPackAuthList;
    }

    private TenantPackAuth toTenantPackAuth(TenantPackAuthDTO tenantPackAuthDTO) {
        if (tenantPackAuthDTO == null) {
            return null;
        }
        TenantPackAuth tenantPackAuth = new TenantPackAuth();
        tenantPackAuth.setCategory(tenantPackAuthDTO.getCategory());
        tenantPackAuth.setAuthName(tenantPackAuthDTO.getAuthName());
        tenantPackAuth.setAuthNote(tenantPackAuthDTO.getAuthNote());
        return tenantPackAuth;
    }

    private SysTenantPackUser toSysTenantPackUser(SysTenantPackUserDTO sysTenantPackUserDTO) {
        if (sysTenantPackUserDTO == null) {
            return null;
        }
        SysTenantPackUser sysTenantPackUser = new SysTenantPackUser();
        sysTenantPackUser.setId(sysTenantPackUserDTO.getId());
        sysTenantPackUser.setPackId(sysTenantPackUserDTO.getPackId());
        sysTenantPackUser.setUserId(sysTenantPackUserDTO.getUserId());
        sysTenantPackUser.setTenantId(sysTenantPackUserDTO.getTenantId());
        sysTenantPackUser.setCreateBy(sysTenantPackUserDTO.getCreateBy());
        sysTenantPackUser.setCreateTime(sysTenantPackUserDTO.getCreateTime());
        sysTenantPackUser.setUpdateBy(sysTenantPackUserDTO.getUpdateBy());
        sysTenantPackUser.setUpdateTime(sysTenantPackUserDTO.getUpdateTime());
        sysTenantPackUser.setRealname(sysTenantPackUserDTO.getRealname());
        sysTenantPackUser.setPackName(sysTenantPackUserDTO.getPackName());
        sysTenantPackUser.setPackCode(sysTenantPackUserDTO.getPackCode());
        sysTenantPackUser.setStatus(sysTenantPackUserDTO.getStatus());
        return sysTenantPackUser;
    }

    private TenantDepartAuthInfoDTO toTenantDepartAuthInfoDTO(TenantDepartAuthInfo info) {
        if (info == null) {
            return null;
        }
        TenantDepartAuthInfoDTO tenantDepartAuthInfoDTO = new TenantDepartAuthInfoDTO();
        tenantDepartAuthInfoDTO.setSuperAdmin(info.isSuperAdmin());
        tenantDepartAuthInfoDTO.setSysTenant(toSysTenantDTO(info.getSysTenant()));
        tenantDepartAuthInfoDTO.setPackCountList(toTenantPackUserCountDTOList(info.getPackCountList()));
        tenantDepartAuthInfoDTO.setPackCodes(info.getPackCodes());
        return tenantDepartAuthInfoDTO;
    }
}
